package com.cy.train.business.service.imp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cy.train.business.domain.DailyTrain;
import com.cy.train.business.domain.DailyTrainTicket;
import com.cy.train.business.domain.DailyTrainTicketExample;
import com.cy.train.business.domain.TrainStation;
import com.cy.train.business.enums.SeatTypeEnum;
import com.cy.train.business.enums.TrainTypeEnum;
import com.cy.train.business.mapper.DailyTrainTicketMapper;
import com.cy.train.business.req.DailyTrainTicketQueryReq;
import com.cy.train.business.req.DailyTrainTicketSaveReq;
import com.cy.train.business.resp.DailyTrainTicketQueryResp;
import com.cy.train.business.service.DailyTrainSeatService;
import com.cy.train.business.service.DailyTrainTicketService;
import com.cy.train.business.service.TrainStationService;
import com.cy.train.common.resp.PageResp;
import com.cy.train.common.util.SnowUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Date: 2024/2/27 14:48
 * @Author: cyzhang
 */
@Service
public class DailyTrainTicketServiceImp implements DailyTrainTicketService {
    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainTicketServiceImp.class);

    @Autowired
    private DailyTrainTicketMapper dailyTrainTicketMapper;

    @Autowired
    private TrainStationService trainStationService;

    @Autowired
    private DailyTrainSeatService dailyTrainSeatService;

    @Override
    public void save(DailyTrainTicketSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrainTicket dailyTrainTicket = BeanUtil.copyProperties(req, DailyTrainTicket.class);
        if(ObjectUtil.isNull(dailyTrainTicket.getId())) {
            dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainTicket.setCreateTime(now);
            dailyTrainTicket.setUpdateTime(now);
            dailyTrainTicketMapper.insert(dailyTrainTicket);
        } else {
            dailyTrainTicket.setUpdateTime(now);
            dailyTrainTicketMapper.updateByPrimaryKeySelective(dailyTrainTicket);
        }

    }

    @Override
    @CachePut("DailyTrainTicketService.queryList")
    public PageResp<DailyTrainTicketQueryResp> queryListCache(DailyTrainTicketQueryReq req) {
        return queryList(req);
    }

    @Override
//    @Cacheable("DailyTrainTicketService.queryList")
    public PageResp<DailyTrainTicketQueryResp> queryList(DailyTrainTicketQueryReq req) {
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.setOrderByClause("id desc");
        DailyTrainTicketExample.Criteria criteria = dailyTrainTicketExample.createCriteria();

        if (ObjUtil.isNotNull(req.getDate())) {
            criteria.andDateEqualTo(req.getDate());
        }
        if (ObjUtil.isNotEmpty(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }
        if (ObjUtil.isNotEmpty(req.getStart())) {
            criteria.andStartEqualTo(req.getStart());
        }
        if (ObjUtil.isNotEmpty(req.getEnd())) {
            criteria.andEndEqualTo(req.getEnd());
        }

        LOG.info("当前页：{}", req.getPage());
        LOG.info("每页数量：{}", req.getSize());

        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrainTicket> dailyTrainTicketList = dailyTrainTicketMapper.selectByExample(dailyTrainTicketExample);

        PageInfo<DailyTrainTicket> pageInfo = new PageInfo<>(dailyTrainTicketList);
        LOG.info("总条数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainTicketQueryResp> dailyTrainTicketQueryRespList = BeanUtil.copyToList(dailyTrainTicketList, DailyTrainTicketQueryResp.class);
        PageResp<DailyTrainTicketQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(dailyTrainTicketQueryRespList);

        return pageResp;
    }

    @Override
    public void delete(Long id) {
        dailyTrainTicketMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void genDaily(DailyTrain dailyTrain,  Date date, String trainCode) {
        //删除指定日期余票数据
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.createCriteria().andDateEqualTo(date).andTrainCodeEqualTo(trainCode);
        dailyTrainTicketMapper.deleteByExample(dailyTrainTicketExample);

        List<TrainStation> list = trainStationService.queryTrainStationByCode(trainCode);

        // 余票
        Long yzd = dailyTrainSeatService.countSeatByTrainCode(date, trainCode, SeatTypeEnum.YDZ.getCode());
        Long edz = dailyTrainSeatService.countSeatByTrainCode(date, trainCode, SeatTypeEnum.EDZ.getCode());
        Long rw = dailyTrainSeatService.countSeatByTrainCode(date, trainCode, SeatTypeEnum.RW.getCode());
        Long yw = dailyTrainSeatService.countSeatByTrainCode(date, trainCode, SeatTypeEnum.YW.getCode());

        BigDecimal trainPriceRate = EnumUtil.getFieldBy(TrainTypeEnum::getPriceRate, TrainTypeEnum::getCode, dailyTrain.getType());

        DateTime now = new DateTime();

        for (int i = 0; i < list.size() - 1; i++) {
            TrainStation trainStationStart = list.get(i);
            BigDecimal sumKM = BigDecimal.ZERO;
            for (int j = i + 1; j < list.size(); j++) {
                TrainStation trainStationEnd = list.get(j);

                // 票价 = 公里 * 座位类型系数 * 车次类型系数
                sumKM = sumKM.add(trainStationEnd.getKm());
                BigDecimal ydzPrice = sumKM.multiply(SeatTypeEnum.YDZ.getPrice()).multiply(trainPriceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal edzPrice = sumKM.multiply(SeatTypeEnum.EDZ.getPrice()).multiply(trainPriceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal rwPrice = sumKM.multiply(SeatTypeEnum.RW.getPrice()).multiply(trainPriceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal ywPrice = sumKM.multiply(SeatTypeEnum.YW.getPrice()).multiply(trainPriceRate).setScale(2, RoundingMode.HALF_UP);

                DailyTrainTicket dailyTrainTicket = new DailyTrainTicket();
                dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
                dailyTrainTicket.setDate(date);
                dailyTrainTicket.setTrainCode(trainCode);
                dailyTrainTicket.setStart(trainStationStart.getName());
                dailyTrainTicket.setStartPinyin(trainStationStart.getNamePinyin());
                dailyTrainTicket.setStartTime(trainStationStart.getOutTime());
                dailyTrainTicket.setStartIndex(trainStationStart.getIndex());
                dailyTrainTicket.setEnd(trainStationEnd.getName());
                dailyTrainTicket.setEndPinyin(trainStationEnd.getNamePinyin());
                dailyTrainTicket.setEndTime(trainStationEnd.getInTime());
                dailyTrainTicket.setEndIndex(trainStationEnd.getIndex());
                dailyTrainTicket.setYdz(Math.toIntExact(yzd));
                dailyTrainTicket.setYdzPrice(ydzPrice);
                dailyTrainTicket.setEdz(Math.toIntExact(edz));
                dailyTrainTicket.setEdzPrice(edzPrice);
                dailyTrainTicket.setRw(Math.toIntExact(rw));
                dailyTrainTicket.setRwPrice(rwPrice);
                dailyTrainTicket.setYw(Math.toIntExact(yw));
                dailyTrainTicket.setYwPrice(ywPrice);
                dailyTrainTicket.setCreateTime(now);
                dailyTrainTicket.setUpdateTime(now);
                dailyTrainTicketMapper.insert(dailyTrainTicket);
            }
        }
    }

    @Override
    public DailyTrainTicket selectUnique(Date date, String code, String start, String end) {
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(code)
                .andStartEqualTo(start)
                .andEndEqualTo(end);
        List<DailyTrainTicket> list = dailyTrainTicketMapper.selectByExample(dailyTrainTicketExample);
        if(CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }
}
